#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include "cJSON.h"

#define N 10240
#define M 10240
int clifd;
void send_node_json_to_server(int server_socket_fd);
void *client_handler(void *arg);
void *udp_broadcast_handler(void *arg);
struct sockaddr_in addr, cliaddr;
socklen_t addrlen = sizeof(cliaddr);
int main(int argc, char const *argv[])
{
    int broadfd, tcpfd;
    ssize_t len;
    char buf[N] = {0};
    // 创建UDP套接字并绑定
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8000);
    addr.sin_addr.s_addr = INADDR_ANY;
    bind(broadfd, (struct sockaddr *)&addr, addrlen);
    printf("UDP bind ok\n");
    // 设置套接字选项以开启广播
    int broadcast = 1;
    if (setsockopt(broadfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) < 0)
    {
        perror("setsockopt (SO_BROADCAST)");
        return -1;
    }
    // 接收"tianwanggaidihu"搜索包
    bzero(buf, N);
    len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);
    printf("recv ok\n");
    // 创建TCP套接字并绑定
    tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8000); // 端口号
    addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }
    if (listen(tcpfd, 5) < 0)
    {
        perror("listen err");
        return -1;
    }
    // 循环接收客户端的连接
    while (1)
    {
        // 判断收到的广播数据是否"tianwanggaidihu"
        if (strcmp(buf, "tianwanggaidihu") == 0)
        {
            printf("is Four Grupe\n");
            //发送baotazhenheyao，告诉软件，我收到了搜索协议，并且回复地址
            sendto(broadfd, "baotazhenheyao", strlen("baotazhenheyao") + 1, 0, (struct sockaddr *)&cliaddr, addrlen);
            printf("wait new client connect\n");
            int clifd = accept(tcpfd, (struct sockaddr *)&cliaddr, &addrlen);
            if (clifd < 0)
            {
                perror("accept err");
                continue; // 继续监听其他连接
            }
            printf("accept ok\n");
            // 创建线程来处理新的客户端连接
            pthread_t thread_id;
            if (pthread_create(&thread_id, NULL, client_handler, (void *)&clifd) != 0)
            {
                perror("pthread_create failed");
                close(clifd);
                continue;
            }
            pthread_detach(thread_id); // 分离线程，自动回收资源
        }
    }
    return 0;
}

void *client_handler(void *arg)
{
    printf("new client is coming\n");
    clifd = *(int *)arg;
    char puf[N] = {0};
    char puf1[N] = {0};
    int recv_n = 0;
    int recv_n2 = 0;
    // 接收点表
    while (1)
    {
        recv_n = recv(clifd, puf, M, 0);
        if (recv_n <= 0)
        {
            perror("recv err");
            break;
        }
        cJSON *root = cJSON_Parse(puf);
        if (root == NULL)
        {
            printf("JSON parse error\n");
        }
        cJSON *item = cJSON_GetObjectItem(root, "type");
        if (item != NULL)
        {
            // 检查node.json文件是否存在
            struct stat buffer;
            if (stat("./node.json", &buffer) == 0)
            {
                // 文件存在，修改type值为3
                item->valueint = 3;
            }
            int type = item->valueint;
            if (type == 1)
            {
                int Atcpfd = socket(AF_INET, SOCK_STREAM, 0);
                struct sockaddr_in Aaddr;
                Aaddr.sin_family = AF_INET;
                Aaddr.sin_port = htons(8001);
                Aaddr.sin_addr.s_addr = INADDR_ANY;
                int Aaddrlen = sizeof(Aaddr);
                if (bind(Atcpfd, (struct sockaddr *)&Aaddr, Aaddrlen) < 0)
                {
                    perror("bind err");
                }
                printf("bind okkk\n");
                if (listen(Atcpfd, 5) < 0)
                {
                    perror("listen err");
                }
                printf("listen okkk\n");
                //连接接受
                int Aclifd = accept(Atcpfd, (struct sockaddr *)&cliaddr, &addrlen);
                // 拷贝配置文件
                int fd = open("./node.json", O_WRONLY | O_CREAT | O_TRUNC, 0777);
                if (fd < 0)
                {
                    perror("open err");
                }
                while (1)
                {
                    recv_n2 = recv(Aclifd, puf1, 10240, 0);
                    printf("%s\n", puf1);
                    if (recv_n2 <= 0)
                    {
                        break;
                    }
                    write(fd, puf1, recv_n2);
                    close(fd);
                    close(Aclifd);
                }
            }
            else if (type == 3)
            {
                // 如果收到心跳包
                printf("recv ok\n");
                if (send(clifd, "heartbeat", strlen("heartbeat"), 0) < 0)
                {
                    perror("send err\n");
                    break;
                }
            }
        }
        cJSON_Delete(root); // 释放 JSON 对象
    }

    // 关闭客户端连接
    close(clifd);
    return NULL;
}
void send_node_json_to_server(int server_socket_fd)
{
    //     // 从node.json中读取内容
    FILE *file = fopen("./node.json", "rb");
    if (file == NULL)
    {
        perror("fopen err");
    }
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *json_data = (char *)malloc(length + 1);
    if (json_data == NULL)
    {
        fclose(file);
        perror("malloc err");
    }
    fread(json_data, 1, length, file);
    fclose(file);
    json_data[length] = '\0';
    // 解析node.json
    cJSON *node_root = cJSON_Parse(json_data);
    free(json_data);
    if (node_root == NULL)
    {
        printf("JSON parse error\n");
    }
    // 查找type==2的内容
    cJSON *node_item = cJSON_GetObjectItem(node_root, "type");
    if (node_item != NULL && node_item->valueint ==2)
    {
        // 将type=2的内容发送给客户端
        char *send_data = cJSON_PrintUnformatted(node_root);
        if (send_data == NULL)
        {
            cJSON_Delete(node_root);
            perror("cJSON print err");
        }
        if (send(clifd, send_data, strlen(send_data), 0) < 0)
        {
            cJSON_Delete(node_root);
            perror("send err");
        }
        free(send_data);
    }
    cJSON_Delete(node_root);
}
